// pages/login/login.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    account: '',
    password: '',
    code: '',
    cookie: '',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // ycD87NotnxRUga8C
    this.setData({
      account: wx.getStorageSync('account'),
      password: wx.getStorageSync('password')
    })
    // wx.redirectTo({
    //     url: '/pages/busmod/busmod',
    //   })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {
    this.getCaptchaImage()
  },
  getCaptchaImage() {
    var _this = this;
    var timeStamp = Date.parse(new Date());
    app.getData("/captcha/captchaImage?type=math&s=" + timeStamp).then(res => {
      // console.log(res.cookies[0].split(';')[0]);
      wx.setStorage({
        key: "cookie",
        data: res.cookies[0].split(';')[0],
      })
      // console.log(res.data);
      let url = 'data:image/png;base64,' + wx.arrayBufferToBase64(res.data);
      _this.setData({
        codeUrl: url
      })
    });
  },
  getAccount: function (e) {
    // console.log(e)
    this.setData({
      account: e.detail.value,
    })
  },
  getPassWord: function (e) {
    this.setData({
      password: e.detail.value,
    })
  },
  getCode: function (e) {
    this.setData({
      code: e.detail.value,
    })
  },
  login() {

    var param = {
      "username": this.data.account,
      "password": this.data.password,
      "validateCode": this.data.code,
      "rememberMe": "true"
    }
    // console.log(param)
    //登录
    app.postData("/login", param).then(res => {
      try {
        if (res.data.code == 0) {
          wx.setStorage({
            key: "account",
            data: param.username,
          })
          wx.setStorageSync('password', param.password)
          console.log(wx.getStorageSync('account'), wx.getStorageSync('password'))
          wx.redirectTo({
            url: '/pages/index/index',
          })
        } else {
          wx.showToast({
            icon: 'error',
            title: res.data.msg,
          })
        }
      } catch (e) {
        wx.showToast({
          icon: 'error',
          title: '登录失败',
        })
      }
    })
  }
})